<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getWebpageList, getWebpageDownloadUrl } from '@/api/webpage'
import { checkLoginStatus } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const interestingPages = ref([])
const loading = ref(false)

// 判断URL是否是图片或可以作为图片资源
const getImageUrl = (page) => {
  // 如果URL明确是图片格式
  if (page.webpageUrl && /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(page.webpageUrl)) {
    return page.webpageUrl
  }
  
  // 固定图片，以后可替换为网站favicon或截图
  return `https://picsum.photos/300/200?random=${page.id}`
}

// 获取网页列表数据
const fetchWebpages = async () => {
  loading.value = true
  interestingPages.value = []
  
  try {
    const result = await getWebpageList()
    
    if (!result) {
      ElMessage.warning('未获取到数据')
      return
    }

    // 处理数据
    if (result.code === 0) {
      // code为0表示请求失败
      ElMessage.error(result.message || '获取网页列表失败')
    } else if (result.code === 200) {
      // code为200表示请求成功
      if (result.data && Array.isArray(result.data)) {
        interestingPages.value = result.data
      } else if (result.data && result.data.data && Array.isArray(result.data.data)) {
        interestingPages.value = result.data.data
      }
    }
  } catch (err) {
    ElMessage.error(err.message || '获取网页列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 处理点击事件，跳转到静态页面
const handleItemClick = (page) => {
  if (!page) {
    return
  }
  
  // 尝试获取标题，检查常见的标题字段
  const pageTitle = page.webpageTitle

  // 构建静态页面的URL路径
  let staticPageUrl = `/static/${pageTitle}/index.html`
  
  // 打开新页面
  window.open(staticPageUrl, '_blank')
}

// 处理下载事件
const handleDownload = async (event, page) => {
  event.stopPropagation() // 阻止事件冒泡，避免触发卡片点击
  
  if (!page || !page.id) {
    ElMessage.error('无法下载，网页ID不存在')
    return
  }
  
  // 检查用户是否已登录
  let isLoggedIn = userStore.id !== null
  
  // 如果本地存储显示已登录，再次确认后端登录状态
  if (isLoggedIn) {
    try {
      const loginResponse = await checkLoginStatus()
      // 如果后端返回未登录，更新本地状态
      if (loginResponse.code === 200 && loginResponse.data === false) {
        userStore.clearUserInfo()
        isLoggedIn = false
      }
    } catch (error) {
      // 检查登录状态出错，继续执行
    }
  }
  
  // 如果未登录，提示用户去登录
  if (!isLoggedIn) {
    ElMessageBox.confirm(
      '下载需要登录，是否前往登录页面？',
      '提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).then(() => {
      // 用户点击确认，跳转到登录页
      router.push('/login')
    }).catch(() => {
      // 用户点击取消，不做操作
    })
    return
  }
  
  // 用户已登录，继续下载流程
  try {
    // 显示加载中指示器
    const loading = ElLoading.service({
      lock: true,
      text: '正在下载压缩包...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用API函数获取下载URL
    const downloadUrl = getWebpageDownloadUrl(page.id)
    
    // 创建一个隐藏的a标签来处理下载
    const link = document.createElement('a')
    link.href = downloadUrl
    
    // 设置下载文件名
    const fileName = page.webpageTitle || page.title || page.name || `页面${page.id}`
    link.download = `${fileName}.zip`
    
    // 将链接添加到文档中并触发点击
    document.body.appendChild(link)
    link.click()
    
    // 清理DOM
    setTimeout(() => {
      document.body.removeChild(link)
      loading.close() // 关闭加载提示
      ElMessage.success('下载已开始')
    }, 500)
  } catch (error) {
    ElMessage.error(`下载失败: ${error.message || '未知错误'}`)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchWebpages()
})
</script>

<template>
  <div class="interesting-page-home">
    <h1 class="page-title">有趣的网页</h1>
    
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div>加载中...</div>
    </div>
    
    <div v-else-if="interestingPages.length === 0" class="empty-message">
      暂无数据
    </div>
    
    <div v-else class="grid-container">
      <div 
        v-for="page in interestingPages" 
        :key="page.id" 
        class="grid-item"
        @click="handleItemClick(page)"
      >
        <div class="item-container">
          <div class="image-container">
            <img 
              :src="getImageUrl(page)" 
              :alt="page.webpageTitle" 
              class="item-image" 
            />
          </div>
          <div class="item-title">{{ page.webpageTitle || page.title || page.name || `页面${page.id}` }}</div>
          <button 
            class="download-button"
            @click="handleDownload($event, page)"
          >
            下载页面
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.interesting-page-home {
  padding: 0;
  max-width: 1200px;
  margin: 0 auto;
  padding-top: 20px; /* 导航栏的空间 */
}

.page-title {
  text-align: left;
  margin-top: 0.5rem;
  margin-bottom: 1.5rem;
  font-size: 2rem;
  background: linear-gradient(45deg, #007cf0, #00dfd8);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  padding-left: 1rem;
}

.grid-container {
  padding: 0 1rem;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 2rem;
}

.grid-item {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.grid-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.item-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.image-container {
  overflow: hidden;
  width: 100%;
}

.item-image {
  width: 100%;
  height: auto;
  object-fit: cover;
}

.item-title {
  padding: 1rem;
  text-align: center;
  font-weight: 500;
  background-color: white;
  font-size: 1.1rem;
  color: #333;
  border-top: 1px solid #f0f0f0;
}

.download-button {
  width: 100%;
  padding: 0.8rem;
  background: linear-gradient(45deg, #007cf0, #00dfd8);
  color: white;
  border: none;
  cursor: pointer;
  font-weight: 500;
  font-size: 1.2rem;
  transition: background-color 0.3s ease;
  margin-top: auto;
}

.download-button:hover {
  background: linear-gradient(45deg, #0070d8, #00c8c8);
}

.download-button:active {
  background: linear-gradient(45deg, #0064c0, #00b4b4);
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4a90e2;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 空数据状态 */
.empty-message {
  text-align: center;
  color: #999;
  padding: 3rem;
  font-size: 1.2rem;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .grid-container {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
}
</style> 